package com.artezio.vacation.dao.hibernate.user;

import com.artezio.vacation.dao.UserDAO;
import com.artezio.vacation.dao.hibernate.HibernateEntityDAOSupport;
import com.artezio.vacation.domain.User;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Set;

/**
 * Hibernate implementation of the user dao
 */
@Repository
public class UserHibernateDAO extends HibernateEntityDAOSupport<User> implements UserDAO {

    @Autowired
    public UserHibernateDAO(SessionFactory sessionFactory) {
        super(User.class, sessionFactory);
    }

    @Override
    public User findUserByEmail(String email) {
        SessionFactory sessionFactory = getSessionFactory();
        Query query = sessionFactory.getCurrentSession().createQuery("from User where email = :email");
        query.setString("email", email);
        User user = (User) query.uniqueResult();
        return user;
    }

    @Override
    public List<User> getAllUsers() {
        SessionFactory sessionFactory = getSessionFactory();
        Query query = sessionFactory.getCurrentSession().createQuery("from User");
        List<User> users = query.list();
        return users;
    }

    @Override
    public List<User> findUsersById(Set<Long> ids) {
        SessionFactory sessionFactory = getSessionFactory();
        Query query = sessionFactory.getCurrentSession().createQuery("from User where userId in (:ids)");
        List<User> users = query.list();
        return  users;
    }

    @Override
    public List<User> findUserByEmailPattern(String emailPattern) {
        SessionFactory sessionFactory = getSessionFactory();
        List<User> users = sessionFactory.getCurrentSession().createCriteria(User.class)
                .add(Restrictions.like("email", emailPattern, MatchMode.END).ignoreCase()).list();
        return users;
    }

//    public static void main(String[] args) {
//        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("test.xml");
//        applicationContext.getBean("userHibernateDAO");
//    }
}
